package com.maiji.cloud.utils;

import com.baidu.aip.contentcensor.AipContentCensor;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.client.RestTemplate;

public class BaiduAI {

    private static final Logger logger = LoggerFactory.getLogger(BaiduAI.class);

    public static final String APP_ID = "18955979";
    public static final String API_KEY = "4mLmzUxAlldelGRhO0uyiRHu";
    public static final String SECRET_KEY = "p5bCKMSX1bynvtMefXsUmODcwbD2mcbR";
    // 初始化一个AipOcr
    public static final AipContentCensor CLIENT = new AipContentCensor(APP_ID, API_KEY, SECRET_KEY);

    static {
        // 可选：设置网络连接参数
        CLIENT.setConnectionTimeoutInMillis(6666);
        CLIENT.setSocketTimeoutInMillis(66666);
    }

    public static Boolean examineText (String text) {
        JSONObject response = new JSONObject();
        try {
            response = CLIENT.textCensorUserDefined(text);
            Integer conclusionType = response.getInt("conclusionType");
            if (conclusionType == 1) return true;
            else {
                JSONArray data = response.getJSONArray("data");
                for (int i = 0; i < data.length(); i++) {
                    JSONObject jsonObject = data.getJSONObject(i);
                    Integer subType = jsonObject.getInt("subType");
                    if (subType != 4) return false;
                }
                return true;
            }
        } catch (Exception e) {
            logger.info("文本审核报错 ===>> text = {}, response = {}", text, response.toString());
        }
        return null;
    }

    public static Boolean examineImg (String url) {
        JSONObject response = new JSONObject();
        try {
            byte[] bytes = new RestTemplate().getForObject(url + "?x-oss-process=image/resize,l_500", byte[].class);
//            JSONObject response = CLIENT.imageCensorUserDefined(url, EImgType.URL, null);
            response = CLIENT.imageCensorUserDefined(bytes, null);
            logger.info("图像审核 ===>> url = {}, response = {}", url, response.toString());
            Integer conclusionType = response.getInt("conclusionType");
            return conclusionType == 1;
        } catch (Exception e) {
            logger.info("图像审核报错 ===>> url = {}, response = {}", url, response.toString());
        }
        return null;
    }
    
    public static void main (String[] args) {
        long start = System.currentTimeMillis();
        System.out.println(examineImg("https://maiji-user-images-2020-2.oss-cn-beijing.aliyuncs.com/81f3418fe9e046748b72de6762c97733.jpg"));
//        System.out.println(examineText("晚餐 随便吃点吧 鸭胸肉炒尖椒 清炒茼蒿菜 黄瓜鸡蛋"));
        System.out.println(System.currentTimeMillis() -start);
    }

}
